//
//  NetWork.swift
//  swift使用AFN网络封装方法
//
//  Created by yangshuo on 15/11/27.
//  Copyright © 2015年 yangshuo. All rights reserved.
//

import UIKit
//swift使用第三方框架import Pods下的文件名
import AFNetworking
//对swift的GET与POST进行封装需要创建一个枚举
enum HMRequest: String{
    //swift枚举使用case,枚举类型不仅局限于整形
    case GET = "GET"
    case POST = "POST"
    
}
class NetWork: AFHTTPSessionManager {
    //定义相关授权信息属性
    private let appKey = "85866419"
    private let appSeret = "41b54d4bc49ad201792c1266910be1e2"
    private let redirectUri = "http://www.baidu.com"
    
    //无论oc还是swift定义 数据类型首字母大写!
    //网络请求回调,类似于OC的typeDefine(定义类型).typealias(别名)
    typealias HMRequestSuccessCallBack = (success: AnyObject?)->()
    typealias HMRequestErrorCallBack = (error: NSError?)->()

    
    //创建一个单例(使用类懒加载方法)
    static let sharedNetWork: NetWork = {
        let tools = NetWork(baseURL: nil)
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return tools
     //swift懒加载一定不要忘了{}的()!!
    }()
    
    //返回token字典
    private var tokenDict: [String: AnyObject]?{//2.返回token字典

        //判断token是否有效
        if let token = UserAccountViewModel.sharedUserAccount.access_token{
        return ["access_token": token]
        }
        return nil
    }

}
// MARK: - 微博数据相关方法
extension NetWork{
    func loadData(successFinish: HMRequestSuccessCallBack, errorFinish: HMRequestErrorCallBack){
        guard let paraments = tokenDict else{
            errorFinish(error:NSError(domain: "ys.xx.error", code: -999, userInfo: ["info": "字典为nil,token无效"]))
            return
        }
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        request(.GET, urlString: urlString, parameters: paraments, successFinish: successFinish, errorFinish: errorFinish)
}
}
// MARK: -用户相关方法
extension NetWork{
    //通过token_access获取用户信息(GET请求)
    /// - see: [http://open.weibo.com/wiki/2/users/show](http://open.weibo.com/wiki/2/users/show)
    func loadUserInfo(uid: String, successFinish:HMRequestSuccessCallBack, errorFinish: HMRequestErrorCallBack){
        //获取token字典
        guard var paraments = tokenDict else{
            //,如果字典为nil,通知调用方,token无效,自定义的错误结果
            errorFinish(error: NSError(domain: "ys.xx.error", code: -999, userInfo: ["info": "字典为nil,token无效"]))
            return
        }
        
        //修改网络方法
     let urlString = "https://api.weibo.com/2/users/show.json"
        //为字典中赋值
       paraments["uid"] = uid
        request(.GET, urlString: urlString, parameters: paraments, successFinish: successFinish, errorFinish: errorFinish)
        
    }
}
//OAuh相关方法
extension NetWork{
    
    var oauhURL: NSURL{//定义一个计算型的属性!,而且extension不允许存储性属性
        //拼接请求验证的url
    let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(appKey)&redirect_uri=\(redirectUri)"
        return NSURL(string: urlString)!
    }
    func loadAccessToken(code: String, successFinish:HMRequestSuccessCallBack, errorFinish:HMRequestErrorCallBack){//在这里进行闭包参数设置,可以直接将参数传给调用方!
    let urlString = "https://api.weibo.com/oauth2/access_token"
        let parameters = ["client_id": appKey,
        "client_secret": appSeret,
        "grant_type": "authorization_code",
        "code": code,
        "redirect_uri": redirectUri
        ]
        //闭包将successFinish与errorFinish参数回调进来
        request(.POST, urlString: urlString, parameters: parameters, successFinish: successFinish, errorFinish: errorFinish)
        
        //测试返回的数据内容 - AFN默认的响应格式是JSON,会直接反序列化成字典
        //如果要确认数据格式的问题,需要自己POST将json数据反序列成字符串
        //1.设置相应的格式是二进制的
//        responseSerializer = AFHTTPResponseSerializer()
//        
//        //2.发起网络请求
//        POST(urlString, parameters: parameters, success: { (_, success) -> Void in
//                        //将二进制数据转成字符串
//            let json = NSString(data: success as!NSData, encoding: NSUTF8StringEncoding)
//            print(json)
//            //"access_token":"2.00ATUHdD0PmRoF6d05247ad8b4yjFC"
//            //"remind_in":"157679999"
//            //"expires_in":157679999
//            //"uid":"3326461014"
//            }, failure: nil)
//        
    }
    

}
// 将AFN方法进行封装
extension NetWork{
    //闭包是可以提前准备好的代码 ,然后在需要的时候执行,可以当做参数,所以可定义一个成功回调与失败回调
    //而且需要注意的是如果闭包想以参数的形式进行传递,类型必须一致!
    
    //
  
    func request(method:HMRequest, urlString: String, parameters: [String: AnyObject]?, successFinish:HMRequestSuccessCallBack, errorFinish: HMRequestErrorCallBack){
        let success1 = { (task: NSURLSessionDataTask,success: AnyObject) -> Void in
            successFinish(success: success)
        }
        let error1 = { (task: NSURLSessionDataTask?,error: NSError) -> Void in
            errorFinish(error: error)
        }
        if method == HMRequest.GET{
            GET(urlString, parameters: parameters, success: success1, failure: error1)
        }else if method == HMRequest.POST{
            POST(urlString, parameters: parameters, success: success1, failure: error1)
        }
        }
}